from createMap import Map
from db import DB
import random


class Layout():
    def __init__(self, floor, level):
        """
        params:
            floor: [int] 楼层
            level: [int] 玩家当前等级
        """
        self.floor = floor  # 楼层编号
        self.level = level  # 玩家等级
        self.__floorINF = DB().get_floor(floor)  # 楼层信息
        self.map = Map(self.__floorINF["width"],
                       self.__floorINF["height"]).mapData()  # 地图数据

        coordinate = self.__get_coordinate()
        self.__space = coordinate[0]  # 通道坐标列表
        self.__wall = coordinate[1]  # 墙坐标列表

        self.__put_item()  # 放道具
        self.__put_monster()  # 放怪物
        self.__put_boss()  # 放boss
        self.__put_hero() # 放角色

    def __put_item(self):
        """
        放置道具
        """
        if self.__floorINF["item"]:
            item_list = self.__floorINF["item"].split(",")

            for i in item_list:
                if self.__space:
                    random.shuffle(self.__space)
                    
                    checked = self.__space[random.randint(0, len(self.__space) - 1)]
                    self.map[checked[0]][checked[1]] = (0, int(i))
                    self.__space.remove(checked)

    def __put_monster(self):
        """
        放置怪物
        """
        monster = self.__choose_monster()
        
        for i in monster:
            if self.__space:
                random.shuffle(self.__space)
                checked = self.__space[random.randint(0, len(self.__space) - 1)]
                self.map[checked[0]][checked[1]] = (1, i)
                self.__space.remove(checked)

    def __put_boss(self):
        """
        放置Boss
        """
        if self.floor % 10 == 0:
            boss = DB().get_boss(self.floor)
            self.map[self.__floorINF["height"] - 1][self.__floorINF["width"] - 2] = (2, boss)
        else:
            self.map[self.__floorINF["height"] - 1][self.__floorINF["width"] - 2] = 2
    
    def __put_hero(self):
        """
        放置玩家初始位置
        """
        self.map[0][1] = 3


    def __choose_monster(self):
        """
        根据玩家等级，随机选择怪物
        """
        monster = DB().get_monster_list(self.level)
        
        monster_list = []
        if monster:
            for __ in range(self.__floorINF["monster"]):
                random.shuffle(monster)
                monster_list.append(monster[random.randint(0, len(monster) - 1)])
        
        return monster_list

    def __get_coordinate(self):
        """
        存储墙和通道坐标
        """
        space = []
        wall = []
        
        for i in range(len(self.map)):
            for j in range(len(self.map[i])):
                if self.map[i][j] == 0:
                    space.append((i, j))
                else:
                    wall.append((i, j))

        return (space, wall)


if __name__ == "__main__":
    l = Layout(10, 10)
    print(l.return_json())
